# -*- coding: utf-8 -*-
"""
Created on Sun May 06 23:27:36 2018

@author: gaokun
"""

from numpy import *

import operator

def readDataFromTxt(txtPath):
    fr = open(txtPath)
    lines = fr.readlines()
    lineNum = len(lines)
    
    dataMat = zeros((lineNum, 3))
    label = []
    index = 0
    
    for line in lines:
        line.strip()
        listFromLine = line.split('\t')
        
        dataMat[index,:] = listFromLine[0:3]
        label.append(listFromLine[-1])
        
        index += 1
    return dataMat,label    


def classify(x, dataSet, label, k):
    s = dataSet.shape[0]
    diffMat = tile(x,(s,1)) - dataSet
    diffMatSq = diffMat ** 2
    diffMatSqSum = diffMatSq.sum(axis=1)
    distance = diffMatSqSum ** 0.5 
    sortDistanceIndex = distance.argsort()
    
    labelCount = {}
    
    for i in range(k):
        curLabel = label(sortDistanceIndex[i])
        labelCount[curLabel] = labelCount.get(curLabel,0) + 1
    
    labelCountSorted = sorted(labelCount, cmp=  lambda x,y:cmp(x[1],y[1]), reverse = True)
    return labelCountSorted.argsort(reverse)[0][0]
    
        